03. Handling Exceptions
Handling Exceptions
ND079 C1 L4 A03 Handling Exceptions
To handle exceptions, we need to write an exception handler. This involves three main components:
- A
tryblock - A
catchblock - A
finallyblock
Here's an example:
try {
read();
}
catch (FileNotFoundException ex){
ex.getLocalizedMessage();
}
finally {
}
In this example, we first try to call the read method to read a file. If that doesn't work, the catch block throws a FileNotFoundException.
Let's take a close look at each component.
The try Block
The try block contains the code we want to try to run. In the example, we are trying to call the read method:
try {
read();
}
The catch Block
A catch block is an exception handler that handles one specific type of Exception. In this example. The type of exception we are handling is a FileNotFoundException exception:
catch (FileNotFoundException ex){
ex.getLocalizedMessage();
}
Remember, FileNotFoundException is a class and—as with all exceptions—it inherits from the Throwable class.
Inside the catch block, we add the code we want to execute when the exception is thrown—in this case, we are calling a method called getLocalizedMessage.
The finally Block
The last component of the handler is the finally block. This is an optional block and, in our example, you can see that it is empty:
finally {
}
The finally block is always executed–even if an unexpected error causes the method to terminate early.
SOLUTION:
- Java uses three different blocks for Exception handlers: `try`, `catch` and `finally`.
- Exception handlers handle one specific Exception class type.
- Exceptions are handled by creating an Exception Handler.